package com.education.ai.service.impl;

import com.education.ai.dao.MediaResourceDao;
import com.education.ai.entity.MediaResource;
import com.education.ai.service.MediaResourceService;
import com.education.ai.service.WanxiangService;
import com.education.ai.util.TeacherContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 多媒体资源服务实现类
 */
@Service
@Slf4j
public class MediaResourceServiceImpl implements MediaResourceService {

    @Autowired
    private MediaResourceDao mediaResourceDao;

    @Autowired
    @Qualifier("tongYiVisionWebClientCustom")
    private WebClient tongYiVisionWebClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private WanxiangService wanxiangService;

    @Value("${tongyi.wanxiang.api.key:${TONGYI_WANXIANG_API_KEY:your-api-key-here}}")
    private String apiKey;

    @Value("${tongyi.wanxiang.api.uri:https://dashscope.aliyuncs.com/api/v1/services}")
    private String apiBaseUri;

    @Value("${tongyi.wanxiang.api.image-model:wanx2.1-t2i-turbo}")
    private String imageModel;

    public MediaResourceServiceImpl() {
        // 直接使用API模型，不需要模拟模式
    }

    @Override
    public List<MediaResource> getAllMediaResources() {
        return mediaResourceDao.findAll();
    }

    @Override
    public MediaResource getMediaResourceById(Long id) {
        return mediaResourceDao.findById(id).orElse(null);
    }

    @Override
    public List<MediaResource> getMediaResourcesByType(String resourceType) {
        return mediaResourceDao.findByResourceType(resourceType);
    }

    @Override
    public List<MediaResource> getMediaResourcesBySubject(String subject) {
        return mediaResourceDao.findBySubject(subject);
    }

    @Override
    public List<MediaResource> getMediaResourcesByGrade(String grade) {
        return mediaResourceDao.findByGrade(grade);
    }

    @Override
    public MediaResource saveMediaResource(MediaResource mediaResource) {
        // 设置关联教师ID
        String currentTeacherId = TeacherContext.getCurrentTeacherId();
        if (currentTeacherId != null && (mediaResource.getTeacherId() == null || mediaResource.getTeacherId().isEmpty())) {
            log.info("为媒体资源关联教师ID: {}", currentTeacherId);
            mediaResource.setTeacherId(currentTeacherId);
        }

        return mediaResourceDao.save(mediaResource);
    }

    @Override
    public void deleteMediaResource(Long id) {
        mediaResourceDao.deleteById(id);
    }

    @Override
    public MediaResource generateImage(String subject, String grade, String topic, String description) {
        log.info("开始生成教学图片: 学科={}, 年级={}, 主题={}", subject, grade, topic);

        try {
            // 构建提示词
            String prompt = String.format(
                "为%s年级%s科目的'%s'主题创建一张教学图片。%s",
                grade, subject, topic, description
            );

            // 使用通义万象服务生成图片
            String imageUrl = wanxiangService.generateImage(prompt);
            log.info("成功生成图片URL: {}", imageUrl);

            // 获取当前教师ID
            String currentTeacherId = TeacherContext.getCurrentTeacherId();

            // 创建并保存多媒体资源
            MediaResource mediaResource = MediaResource.builder()
                .subject(subject)
                .grade(grade)
                .topic(topic)
                .resourceType("IMAGE")
                .title(topic + "教学图片")
                .description(description)
                .url(imageUrl)
                .format("jpg")
                .createdTime(LocalDateTime.now())
                .build();

            // 设置教师ID
            if (currentTeacherId != null) {
                log.info("为生成的图片关联教师ID: {}", currentTeacherId);
                mediaResource.setTeacherId(currentTeacherId);
            }

            MediaResource savedResource = mediaResourceDao.save(mediaResource);
            log.info("成功生成教学图片, ID: {}", savedResource.getId());
            return savedResource;

        } catch (Exception e) {
            log.error("生成教学图片时发生错误", e);
            throw new RuntimeException("生成教学图片失败: " + e.getMessage(), e);
        }
    }

    @Override
    public MediaResource generateVideo(String subject, String grade, String topic, String description, Integer duration) {
        log.info("开始生成教学视频: 学科={}, 年级={}, 主题={}, 时长={}秒", subject, grade, topic, duration);
        
        // 调用带teacherId参数的方法，并从当前上下文获取教师ID
        return generateVideo(subject, grade, topic, description, duration, TeacherContext.getCurrentTeacherId());
    }
    
    @Override
    public MediaResource generateVideo(String subject, String grade, String topic, String description, Integer duration, String teacherId) {
        log.info("开始生成教学视频: 学科={}, 年级={}, 主题={}, 时长={}秒, 教师ID={}", subject, grade, topic, duration, teacherId);

        try {
            // 构建提示词
            String prompt = String.format(
                "为%s年级%s科目的'%s'主题创建一个教学视频。%s",
                grade, subject, topic, description
            );

            // 使用通义万象服务生成视频
            String videoUrl = wanxiangService.generateVideo(prompt, duration);
            log.info("成功生成视频URL: {}", videoUrl);

            MediaResource mediaResource = MediaResource.builder()
                .subject(subject)
                .grade(grade)
                .topic(topic)
                .resourceType("VIDEO")
                .title(topic + "教学视频")
                .description(description)
                .url(videoUrl)
                .duration(duration)
                .format("mp4")
                .createdTime(LocalDateTime.now())
                .build();

            // 设置教师ID
            if (teacherId != null && !teacherId.isEmpty()) {
                log.info("为生成的视频关联教师ID: {}", teacherId);
                mediaResource.setTeacherId(teacherId);
            }

            MediaResource savedResource = mediaResourceDao.save(mediaResource);
            log.info("成功生成教学视频, ID: {}", savedResource.getId());
            return savedResource;

        } catch (Exception e) {
            log.error("生成教学视频时发生错误", e);
            throw new RuntimeException("生成教学视频失败: " + e.getMessage(), e);
        }
    }

    @Override
    public MediaResource generateImageWithWanxiang(String subject, String grade, String topic, String description, int imageCount, String size, String teacherId) {
        try {
            log.info("使用通义万象生成图片，学科: {}, 年级: {}, 主题: {}, 描述: {}, 图片数量: {}, 尺寸: {}", subject, grade, topic, description, imageCount, size);

            // 检查参数
            if (subject == null || subject.trim().isEmpty()) {
                throw new IllegalArgumentException("学科不能为空");
            }

            if (grade == null || grade.trim().isEmpty()) {
                throw new IllegalArgumentException("年级不能为空");
            }

            if (topic == null || topic.trim().isEmpty()) {
                throw new IllegalArgumentException("主题不能为空");
            }

            if (description == null) {
                description = ""; // 使用空字符串代替null
            }

            if (imageCount <= 0) {
                imageCount = 1;
            }

            // 验证并修正size格式
            if (size == null || size.trim().isEmpty() || !size.contains("*")) {
                log.warn("Size格式错误或为空，使用默认值: 1024*1024");
                size = "1024*1024";
            }

            // 检查API密钥是否配置
            if (apiKey == null || apiKey.equals("your-api-key-here")) {
                log.error("API密钥未配置，请在application.properties中设置tongyi.vision.api.key");
                throw new RuntimeException("API密钥未正确配置");
            }

            // 构建完整提示词
            String prompt = String.format(
                "为%s年级%s科目的'%s'主题创建一张教学图片。%s",
                grade, subject, topic, description
            );

            log.debug("生成的prompt: {}", prompt);

            // 发送请求 - 使用正确的API URL，与WanxiangServiceImpl保持一致
            String apiUrl = apiBaseUri + "/" + imageModel;
            log.debug("请求URL: {}", apiUrl);
            
            // 创建RestTemplate实例
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 构建请求体 - 与WanxiangServiceImpl保持一致
            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> input = new HashMap<>();
            Map<String, Object> parameters = new HashMap<>();
            
            input.put("prompt", prompt);
            
            parameters.put("style", "photographic");
            parameters.put("size", size);
            parameters.put("n", imageCount);
            
            requestBody.put("model", imageModel);
            requestBody.put("input", input);
            requestBody.put("parameters", parameters);
            
            log.debug("请求头: {}", headers);
            log.debug("请求体: {}", requestBody);
            
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, request, String.class);
            
            log.debug("API响应状态码: {}", response.getStatusCode());
            String responseBody = response.getBody();
            log.debug("API响应体: {}", responseBody);
            
            // 解析JSON响应
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonResponse = mapper.readTree(responseBody);
            String imageUrl = jsonResponse.path("output").path("url").asText();
            
            if (imageUrl != null && !imageUrl.isEmpty()) {
                log.info("成功获取生成的图片URL: {}", imageUrl);
                
                // 创建并保存媒体资源
                MediaResource mediaResource = MediaResource.builder()
                    .subject(subject)
                    .grade(grade)
                    .topic(topic)
                    .resourceType("IMAGE")
                    .title(topic + "教学图片")
                    .description(description)
                    .url(imageUrl)
                    .format("jpg")
                    .teacherId(teacherId)
                    .createdTime(LocalDateTime.now())
                    .build();
                
                MediaResource savedResource = mediaResourceDao.save(mediaResource);
                log.info("成功保存生成的图片资源, ID: {}", savedResource.getId());
                return savedResource;
            } else {
                log.error("响应中未包含图片URL: {}", responseBody);
                throw new RuntimeException("生成图片失败: 响应中未包含图片URL");
            }
        } catch (Exception e) {
            log.error("使用通义万象生成图片时发生错误", e);
            throw new RuntimeException("生成图片失败: " + e.getMessage(), e);
        }
    }

    private String waitForTaskCompletion(String taskId, RestTemplate restTemplate, HttpHeaders headers) {
        log.info("等待任务完成, 任务ID: {}", taskId);
        
        final String statusCheckUrl = "https://dashscope.aliyuncs.com/api/v1/tasks/" + taskId;
        final int MAX_RETRIES = 30;
        final int RETRY_INTERVAL_MS = 2000;
        
        for (int i = 0; i < MAX_RETRIES; i++) {
            try {
                Thread.sleep(RETRY_INTERVAL_MS);
                
                HttpEntity<Void> requestEntity = new HttpEntity<>(headers);
                ResponseEntity<Map> response = restTemplate.exchange(
                    statusCheckUrl,
                    HttpMethod.GET,
                    requestEntity,
                    Map.class
                );
                
                Map<String, Object> responseBody = response.getBody();
                if (responseBody == null) {
                    log.warn("状态检查响应为空");
                    continue;
                }
                
                log.debug("任务状态响应: {}", responseBody);
                
                if (responseBody.containsKey("output")) {
                    Map<String, Object> output = (Map<String, Object>) responseBody.get("output");
                    String status = (String) output.get("status");
                    
                    if ("SUCCEEDED".equals(status)) {
                        log.info("任务成功完成");
                        
                        if (output.containsKey("url")) {
                            String resultUrl = (String) output.get("url");
                            log.info("获取到结果URL: {}", resultUrl);
                            return resultUrl;
                        }
                    } else if ("FAILED".equals(status)) {
                        log.error("任务失败: {}", output.get("message"));
                        throw new RuntimeException("生成任务失败: " + output.get("message"));
                    } else {
                        log.debug("任务正在进行中, 状态: {}, 重试次数: {}", status, i + 1);
                    }
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("等待任务完成时被中断", e);
                throw new RuntimeException("任务等待被中断", e);
            } catch (Exception e) {
                log.error("检查任务状态时发生错误", e);
                // 继续重试
            }
        }
        
        log.error("达到最大重试次数，任务未完成");
        throw new RuntimeException("任务处理超时，请稍后再试");
    }

    @Override
    public Page<MediaResource> getMediaResourcesByTeacherId(String teacherId, Pageable pageable) {
        if (teacherId == null || teacherId.isEmpty()) {
            return new PageImpl<>(new ArrayList<>());
        }
        
        // 获取当前页的数据
        int offset = (int) pageable.getOffset();
        int pageSize = pageable.getPageSize();
        
        // 获取指定教师的所有资源
        List<MediaResource> allResources = mediaResourceDao.findByTeacherId(teacherId);
        
        // 计算总数
        long total = allResources.size();
        
        // 分页处理
        int fromIndex = Math.min(offset, allResources.size());
        int toIndex = Math.min(offset + pageSize, allResources.size());
        
        List<MediaResource> pagedResources = fromIndex < toIndex 
            ? allResources.subList(fromIndex, toIndex) 
            : new ArrayList<>();
            
        return new PageImpl<>(pagedResources, pageable, total);
    }
} 